<?php
/**
* @filename source_class.php 2013-11-11 02:10:56x
* @author Huming Xu <huming17@126.com>
* @version 1.0.0
* @copyright DZF (c) 2013, Huming Xu
*/
if(!defined('IN_SITE')) {
	exit('Access Denied');
}
class upload_main{
	public $info_array = array();
	public $page_array = array();
	public $tree_array = array();

	static function &instance() {
		static $object;
		if(empty($object)) {
			$object = new self();
		}
		return $object;
	}
    
	public function jsonString($str)
    {
        return preg_replace("/([\\\\\/'])/",'\\\$1',$str);
    }
    public function formatBytes($bytes) {
        if($bytes >= 1073741824) {
            $bytes = round($bytes / 1073741824 * 100) / 100 . 'GB';
        } elseif($bytes >= 1048576) {
            $bytes = round($bytes / 1048576 * 100) / 100 . 'MB';
        } elseif($bytes >= 1024) {
            $bytes = round($bytes / 1024 * 100) / 100 . 'KB';
        } else {
            $bytes = $bytes . 'Bytes';
        }
        return $bytes;
    }

    public function upload_file($src_file,$target_file){
        @copy($src_file,$target_file);
        if(!file_exists($target_file) && function_exists('move_uploaded_file'))
        {
            @move_uploaded_file($src_file,$target_file);
        }
        if(!file_exists($target_file))
        {
            if (@is_readable($src_file) && (@$fp_s = fopen($src_file, 'rb')) && (@$fp_t = fopen($target_file, 'wb'))) {
                while (!feof($fp_s)) {
                    $s = @fread($fp_s, 1024 * 512);
                    @fwrite($fp_t, $s);
                }
                fclose($fp_s); fclose($fp_t);
            }
        }
    }

    //debug 远程抓取图片函数 start
    public function saveRemoteImg($sUrl){
        global $upExt,$maxAttachSize;
        $reExt='('.str_replace(',','|',$upExt).')';
        if(substr($sUrl,0,10)=='data:image'){
            //base64google图片
            if(!preg_match('/^data:image\/'.$reExt.'/i',$sUrl,$sExt))return false;
            $sExt=$sExt[1];
            $imgContent=base64_decode(substr($sUrl,strpos($sUrl,'base64,')+7));
        }
        else{
            //url图片
            if(!preg_match('/\.'.$reExt.'$/i',$sUrl,$sExt))return false;
            $sExt=$sExt[1];
            $imgContent=$this->getUrl($sUrl);
        }
        if(strlen($imgContent)>$maxAttachSize)return false;
        $sLocalFile=$this->getLocalPath($sExt);
        file_put_contents($sLocalFile,$imgContent);
        //DEBUG mime php.ini gd2
        $fileinfo= @getimagesize($sLocalFile);
        if(!$fileinfo||!preg_match("/image\/".$reExt."/i",$fileinfo['mime'])){
            @unlink($sLocalFile);
            return false;
        }
        return $sLocalFile;
    }
    //抓URL
    public function getUrl($sUrl,$jumpNums=0){
        $arrUrl = parse_url(trim($sUrl));
        if(!$arrUrl)return false;
        $host=$arrUrl['host'];
        $port=isset($arrUrl['port'])?$arrUrl['port']:80;
        $path=$arrUrl['path'].(isset($arrUrl['query'])?"?".$arrUrl['query']:"");
        $fp = @fsockopen($host,$port,$errno, $errstr, 30);
        if(!$fp)return false;
        $output="GET $path HTTP/1.0\r\nHost: $host\r\nReferer: $sUrl\r\nConnection: close\r\n\r\n";
        stream_set_timeout($fp, 60);
        @fputs($fp,$output);
        $Content='';
        while(!feof($fp))
        {
            $buffer = fgets($fp, 4096);
            $info = stream_get_meta_data($fp);
            if($info['timed_out'])return false;
            $Content.=$buffer;
        }
        @fclose($fp);
        global $jumpCount;
        if(preg_match("/^HTTP\/\d.\d (301|302)/is",$Content)&&$jumpNums<5)
        {
            if(preg_match("/Location:(.*?)\r\n/is",$Content,$murl))return $this->getUrl($murl[1],$jumpNums+1);
        }
        if(!preg_match("/^HTTP\/\d.\d 200/is", $Content))return false;
        $Content=explode("\r\n\r\n",$Content,2);
        $Content=$Content[1];
        if($Content)return $Content;
        else return false;
    }

    public function getLocalPath($sExt){
        global $dirType,$attachDir;
        switch($dirType)
        {
            case 1: $attachSubDir = 'day_'.date('Ymd'); break;
            case 2: $attachSubDir = 'month_'.date('Ym'); break;
            case 3: $attachSubDir = 'ext_'.$sExt; break;
        }
        $newAttachDir = $attachDir.'/'.$attachSubDir;
        if(!is_dir($newAttachDir))
        {
            @mkdir($newAttachDir, 0777);
            @fclose(fopen($newAttachDir.'/index.htm', 'w'));
        }
        PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
        $newFilename=date("YmdHis").mt_rand(1000,9999).'.'.$sExt;
        $targetPath = $newAttachDir.'/'.$newFilename;
        return $targetPath;
    }
    //debug 远程抓取图片函数 end
    
	/*
	* ajax 返回信息
	*/
	public function return_json($error,$message,$output=1) {
		$return_array = array(
			"error" => $error,
			"message" => $message
		);
		if($output){
			echo json_ext($return_array);
			die;
		}else{
			return json_ext($return_array);
		}
	}
	
	/*
	 * 添加apk文件
	 * 
	 */
	public function add_apk($table_name, $insert_data = array()) {
		$insert_id = '';
		if ($table_name && $insert_data) {
			$sql = "SELECT * FROM " . DB::table($table_name) . " WHERE version = ".$insert_data['version']." LIMIT 1";
			$info = DB::fetch_first($sql);
			if($info){
				return $insert_id;
			}else{
				//原来的版本都为旧
				$update_data['is_new'] = 0;
				$where['is_new'] = 1;
				$effect_row = DB::update($table_name, $update_data, $where);
				
				$insert_id = DB::insert($table_name, $insert_data, true);
			}
		}
		return $insert_id;
	}
	
	/*
	 * 	验证apk是否最新
	 */
	
	public function is_new($table_name, $key_name, $key_id = '') {
		$info = array();
		if ($table_name && $key_name && $key_id) {
			$sql = "SELECT * FROM " . DB::table($table_name) . " WHERE " . $key_name . "='" . $key_id . "' and isdelete = 0 LIMIT 1";
			$info = DB::fetch_first($sql);	
		}
		return $info;
	}
	
	/*
	 * 	获取最新apk数据
	 */
	
	public function get_new($table_name, $key_name, $key_id = '') {
		$info = array();
		if ($table_name && $key_name && $key_id) {
			$sql = "SELECT * FROM " . DB::table($table_name) . " WHERE " . $key_name . "='" . $key_id . "' and isdelete = 0 LIMIT 1";
			$info = DB::fetch_first($sql);
		}
		return $info;
	}
	
	/*
	 *  删除信息
	 */
	public function delete($table_name,$where) {
		$return='';
		if($table_name && $where){
			//$return = DB::delete($table_name, $where, $limit=1);
			
			//TODO 逻辑删需要创建isdelete字段 0=未删除 1=已删除
			$return=DB::update($table_name,array("isdelete"=>1,"modify_dateline"=>TIMESTAMP),$where, $limit=1);			
			//检验是否删除最新的文件
			if($return){
				$sql = "SELECT * FROM " . DB::table($table_name) . " WHERE a_id = " . $where['a_id'] . " LIMIT 1";
				$info = DB::fetch_first($sql);
				if($info['is_new'] == 1){
					$sql = "SELECT * FROM " . DB::table($table_name) . " WHERE isdelete =  0 order by create_dateline desc LIMIT 1";
					$new_info = DB::fetch_first($sql);
					if($new_info['a_id']){
						$new_where['a_id']= $new_info['a_id'];
						DB::update($table_name,array("is_new"=>1,"modify_dateline"=>TIMESTAMP),$new_where, $limit=1);
					}
				}
			}
		}
		return $return;
	}
	
	/*
	 *  列表信息
	 *
	 * @param $table_name string.
	 * @param $page_condition array.
	 *
	 * @return array
	 */
	public function apk_list($table_name,$page_condition){
		$page_result = $info = array();
		$page = $page_condition['page'];
		$limit = $page_condition['limit'];
		$perpage = $page_condition['perpage'];
		$start=(($page-1) * $perpage);
		$wheresql = $page_condition['wheresql'];
		$orderby = $page_condition['orderby'];
		
		$sql = "SELECT * FROM ".DB::table($table_name)." 			
				WHERE 1=1 ".$wheresql." ".$page_condition['orderby']." ".DB::limit($start, $limit);
		$info = DB::fetch_all($sql);
		if($info){
			foreach ($info as $key=>$val){
				if($val['a_name']){
					$info[$key]['url']='http://webapi.jxzhjy.com/data/upload/apk/'.$val['a_name'];
				}else{
					$info[$key]['url']='';
				}
			}
		} 
		
		$sql_total_rows = "SELECT count(*) FROM ".DB::table($table_name)." cn WHERE 1=1 ".$wheresql."";
		$sql_total_rows_result = DB::result_first($sql_total_rows);
		//DEBUG 列表数据返回结构
		$page_result = array(
				'page_now'     => $page,
				'total_page'=>max(1, ceil($sql_total_rows_result/$perpage)),
				//int 返回结果总数
				'total_rows' => $sql_total_rows_result,
				//array 一页数据数组
				'page_data' => $info
		);
		return $page_result;
	}
}
?>